import { NavigationGuardNext, RouteLocationNormalized, createRouter, createWebHistory } from 'vue-router'
import { constantRoute, asyncRouter, anyRoute } from './routes'
import pinia from '@/store'
import useUserStore from '@/store/user'
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'
import LocalForageInstance from '@/utils/localforage';

const db = LocalForageInstance.getInstance();
// const loginStore = useUserStore(pinia)
let loginStore: any = null;
const LOGIN_PATH = '/login'

// 初始化 loginStore
function initLoginStore() {
  if (!loginStore) {
    loginStore = useUserStore(pinia);
  }
}

// 创建路由实例
const router = createRouter({
  history: createWebHistory(), // 使用hash模式
  routes: constantRoute // 静态路由
})

// 重置路由
const resetAndRedirect = async (to: RouteLocationNormalized, next: NavigationGuardNext) => {
  try {
    const routesValue = await db.getdb('routes');
    if (!routesValue) {
      await loginStore.userlogout();
    }
    initLoginStore();
    const decryptedRoutes = loginStore.decrypt(routesValue);
    const filterRoutes = loginStore.filterAsyncRoutes(cloneDeep(asyncRouter), decryptedRoutes); // 过滤异步路由
    loginStore.userr_all_routes = [...constantRoute, ...filterRoutes, anyRoute]; // 合并路由
    loginStore.resetRouter([...filterRoutes, anyRoute]); // 重置路由

    const buttonsValue = await db.getdb('buttons');
    loginStore.buttons = loginStore.decrypt(buttonsValue);

    const usernameValue = await db.getdb('username');
    if (usernameValue) {
      loginStore.username = usernameValue;
      next({ ...to, replace: true });
    } else {
      await loginStore.userlogout();
      next({ ...to, replace: true });
    }
  } catch (error) {
    console.error('重置路由时出错:', error);
    await loginStore.userlogout();
    next({ ...to, replace: true });
  }
}


// 路由前置钩子
router.beforeEach((to, _from, next) => {
  initLoginStore();
  if (loginStore.access_token) {
    if (to.path === LOGIN_PATH) {
      next('/')
    } else {
      loginStore.username ? next() : resetAndRedirect(to, next)
    }
  } else {
    to.path == LOGIN_PATH ? next() : next(LOGIN_PATH)
  }
})


// 路由后置钩子
router.afterEach((to, _from) => {
  document.title = (to.meta.title as string) || 'VueBMS'
})

export default router
